<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="数据库约束">
<meta property="og:type" content="article">
<meta property="og:title" content="Java日拱一卒-day13">
<meta property="og:url" content="http://yoursite.com/2020/05/02/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day13/index.html">
<meta property="og:site_name" content="很惭愧，就做了一点微小的工作">
<meta property="og:description" content="数据库约束">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-05-02T05:16:14.000Z">
<meta property="article:modified_time" content="2020-05-17T15:42:27.589Z">
<meta property="article:author" content="文予">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yoursite.com/2020/05/02/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day13/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Java日拱一卒-day13 | 很惭愧，就做了一点微小的工作</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">很惭愧，就做了一点微小的工作</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">念念不忘，必有回响</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/05/02/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day13/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/wenyu.png">
      <meta itemprop="name" content="文予">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="很惭愧，就做了一点微小的工作">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java日拱一卒-day13
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-05-02 13:16:14" itemprop="dateCreated datePublished" datetime="2020-05-02T13:16:14+08:00">2020-05-02</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-17 23:42:27" itemprop="dateModified" datetime="2020-05-17T23:42:27+08:00">2020-05-17</time>
              </span>

          
            <div class="post-description">数据库约束</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>所有的关系型数据库度支持对数据表使用约束，通过约束可以更好的保证表里数据的完整性。约束是在表上强制执行的数据校验规则，约束主要用于保证数据库里数据的完整性。此外，当表中数据存在相互依赖时，可以保护相关数据不被删除。<br>大部分数据库支持以下5种完整性约束</p>
<ul>
<li><code>NOT NULL</code>：非空约束，指定某列不能为空</li>
<li><code>UNIQUE</code>：唯一约束，指定某列或几列组合不能重复</li>
<li><code>PRIMARY KEY</code>：主键，指定该列的值可以唯一地标识该条记录</li>
<li><code>FOREIGN KEY</code>：外键，指定该行记录从属于主表的一条记录</li>
<li><code>CHECK</code>：检查，指定一个布尔表达式，用于指定对应列的值必须满足该表达式</li>
</ul>
<p>事实上<code>MySQL</code>不支持<code>CHECK</code>约束，虽然在<code>MySQL</code>的SQL语句中可以使用<code>CHECK</code>约束，但是并不会起作用。</p>
<p>约束作为一种数据库对象，被存储在系统表中，有自己的名字。根据对数据列的限制，约束分为两类：</p>
<ul>
<li>单列约束：每个约束只约束一列</li>
<li>多列约束：每个约束可以约束多个数据列<br>为数据库指定约束有两个时机：</li>
<li>建表的同时为相应数据指定约束</li>
<li>建表后创建，以修改表的方式增加约束</li>
</ul>
<p>MySQL使用<code>information_schema</code>数据库里的<code>TABLE_CONSTRAINTS</code>表来保存该数据库实例中的所有约束信息，用户可以查询该表来获取该数据库的约束信息。</p>
<h2 id="NOT-NULL约束"><a href="#NOT-NULL约束" class="headerlink" title="NOT NULL约束"></a><code>NOT NULL</code>约束</h2><p>非空约束用于确保指定列不为空，非空约束是比较特殊的约束：只能作为列级约束使用，只能使用列级约束语法定义。SQL中的<code>null</code>不区分大小写，并且具有以下特征：</p>
<ul>
<li>所有数据类型的值都可以是<code>null</code></li>
<li>与java类似，空字符串不等于<code>null</code>，0也不等于<code>null</code></li>
</ul>
<p>在建表时为指定列指定非空约束，只要在列定义后增加<code>not null</code>即可</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> hehe (</span><br><span class="line">    <span class="comment"># 建立了非空约束，意味着hehe_id不可以为null</span></span><br><span class="line">    hehe_id <span class="built_in">int</span> <span class="keyword">not</span> <span class="literal">null</span>,</span><br><span class="line">    <span class="comment"># MySQL的非空约束不能指定名字</span></span><br><span class="line">    hehe_name <span class="built_in">varchar</span>(<span class="number">255</span>) <span class="keyword">default</span> <span class="string">'xyz not null,</span></span><br><span class="line"><span class="string">    # 下面列可以为空</span></span><br><span class="line"><span class="string">    hehe_gender varchar(2) null</span></span><br><span class="line"><span class="string">);</span></span><br></pre></td></tr></table></figure>

<p>也可使用<code>alter table</code>修改表时增加或者删除非空约束</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 增加非空约束</span></span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> hehe <span class="keyword">modify</span> hehe_gender <span class="built_in">varchar</span>(<span class="number">2</span>) <span class="keyword">not</span> <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 取消非空约束</span></span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> hehe <span class="keyword">modify</span> hehe_name <span class="built_in">varchar</span>(<span class="number">2</span>) <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 取消非空约束并指定默认值</span></span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> hehe <span class="keyword">modify</span> hehe_name <span class="built_in">varchar</span>(<span class="number">255</span>) <span class="keyword">default</span> <span class="string">'abc</span></span><br><span class="line"><span class="string">null;</span></span><br></pre></td></tr></table></figure>

<h2 id="UNIQUE约束"><a href="#UNIQUE约束" class="headerlink" title="UNIQUE约束"></a><code>UNIQUE</code>约束</h2><p>唯一约束的列不能出现重复值，但是可以出现多个<code>null</code>。同一个表内可以创建多个唯一约束，唯一约束也可由多列组成。当为某列创建唯一约束时，MySQL会为该列相应的创建唯一索引。如果不给唯一约束起名，该唯一约束默认与列名相同。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> unique_test (</span><br><span class="line">    <span class="comment"># 建立了非空约束，test_id不可为null</span></span><br><span class="line">    test_id <span class="built_in">int</span> <span class="keyword">not</span> <span class="literal">null</span>,</span><br><span class="line">    <span class="comment"># unique就是唯一约束，使用列级语法建立唯一约束</span></span><br><span class="line">    test_name <span class="built_in">varchar</span>(<span class="number">255</span>) <span class="keyword">unique</span></span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<p>如果需要为多列组合建立唯一约束，或是自行指定约束名，需要用表级约束语法，既可以放在<code>create table</code>语句中与列定义宾咧，也可放在<code>alter table</code>中用<code>add</code>关键字添加约束</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[constraint 约束名] 约束定义</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> unique_test3(</span><br><span class="line">    <span class="comment"># 建立了非空约束，意味着test_id不为null</span></span><br><span class="line">    test_id <span class="built_in">int</span> <span class="keyword">not</span> <span class="literal">null</span>,</span><br><span class="line">    test_name <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    test_pass <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 使用表级约束语法</span></span><br><span class="line">    <span class="keyword">unique</span> (test_name),</span><br><span class="line">    <span class="comment"># 使用表级约束语法建立唯一约束，并指定约束名</span></span><br><span class="line">    <span class="keyword">constraint</span> test2_uk <span class="keyword">unique</span>(test_pass)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<p>也可以为两列组合建立唯一约束，要求两列组合不能重复</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">constraint test3_uk unique(test_name,test_pass)</span><br></pre></td></tr></table></figure>

<p>也可以在修改表结构的时候使用<code>add</code>关键字，或者修改表的时候用<code>modify</code>关键字，为单列增加唯一约束</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> unique_test3 <span class="keyword">add</span> <span class="keyword">unique</span>(test_name,test_pass);</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> unique_test3 <span class="keyword">modify</span> test_name <span class="built_in">varchar</span>(<span class="number">255</span>) <span class="keyword">unique</span>;</span><br></pre></td></tr></table></figure>

<h2 id="PRIMARY-KEY约束"><a href="#PRIMARY-KEY约束" class="headerlink" title="PRIMARY KEY约束"></a><code>PRIMARY KEY</code>约束</h2><p>主键约束相当于非空约束和唯一约束，即主键约束的列不允许重复值也不允许<code>null</code>值。多列组合建立主键约束，则每一列都不能为空，列组合不能重复。主键列的值可以用于唯一标示表中的一条记录。每个表最多允许一个主键，但是主键约束可由多个数据列组成。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> stu(</span><br><span class="line">    <span class="keyword">id</span> <span class="built_in">int</span> primary <span class="keyword">key</span>,</span><br><span class="line">    ...</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<p>如果主键是数值类型，为了方便插入主键（并且保证插入数据时，主键不会因为重复而报错），可以设置一个主键自增策略。<br>主键自增策略是指：设置了自增策略的主键，可以在插入记录时，不给id赋值，只需要设置一个null值，数据库会自动为id分配一个值(AUTO_INCREMENT变量，默认从1开始，后面依次+1)，这样既可以保证id是唯一的，也省去了设置id的麻烦。<br>将id主键设置为自增：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> stu(</span><br><span class="line">    <span class="keyword">id</span> <span class="built_in">int</span> primary <span class="keyword">key</span> auto_increment,</span><br><span class="line">    ...</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<h2 id="FOREIGN-KEY约束"><a href="#FOREIGN-KEY约束" class="headerlink" title="FOREIGN KEY约束"></a><code>FOREIGN KEY</code>约束</h2><p>外键约束主要用于保证一个或两个数据表之间的参照完整性，外键是构建于一个表的两个字段或者两个表的两个字段之间的参照关系：子表外键列的值必须在主表被参照列的值的范围内，或者为空（也可以通过非空约束来约束外键列不为空）</p>
<p>当主表的记录被从表记录参照时，主表记录不允许被删除，必须先把从表里参照该记录的所有记录全部删除后，才可以删除主表的记录。或者删除主表记录时级联删除从表中所有参照该记录的从表记录。<br>从表外键参照的只能是主表的主键列或者唯一键列，这样才能保证从表记录可以准确定位到被参照的主表记录。同一个表内可以拥有多个外键。</p>
<p>外键约束通常用于定义两个实体之间的一对多、多对一的关联关系。对于一对多的关联关系，通常在多的一端增加外键列。例如老师-学生（假设一个老师对应多个学生，一个学生对应一个老师）。为了建立关联关系，可以在学生表增加一个外键列。增加外键列的表称为从表，只要为外键列增加唯一约束就可以表示一对一的关联关系了。对于多对多的关联关系，则需要额外添加一个连接表来记录关联关系。</p>
<p>采用列级约束语法建立外键约束世界使用<code>reference</code>关键字，指定该列参照哪个主表的哪一列</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 为了保证从表参照的主表存在，通常应该先建主表</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> teacher_table (</span><br><span class="line">    <span class="comment"># auto_increment代表数据库的自动编号策略，通常用作数据表的逻辑主键</span></span><br><span class="line">    teacher_id <span class="built_in">int</span> auto_increment,</span><br><span class="line">    teacher_name <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    primary <span class="keyword">key</span>(teacher_id)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> student_table (</span><br><span class="line">    <span class="comment"># 为本表建立主键约束</span></span><br><span class="line">    student_id <span class="built_in">int</span> auto_increment primary <span class="keyword">key</span>,</span><br><span class="line">    student_name <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    <span class="comment"># 指定java_teacher参照到teacher_table的teacher_id列</span></span><br><span class="line">    java_teacher <span class="built_in">int</span> <span class="keyword">references</span> teacher_table(teacher_id)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<p>如果使用表级约束语法，则需要使用<code>foreign key</code>来指定本表的外键列，并使用<code>reference</code>来指定参照哪个主表的哪个数据列。使用表级约束语法可以为外键约束指定约束名，如果未指定，MySQL会为该外键约束命名为<code>table_name_ibfk_n</code></p>
<p>使用<code>constraint</code>显式指定外键约束的名字</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 为了保证从表参照的主表存在，通常应该先建主表</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> teacher_table (</span><br><span class="line">    <span class="comment"># auto_increment代表数据库的自动编号策略，通常用作数据表的逻辑主键</span></span><br><span class="line">    teacher_id <span class="built_in">int</span> auto_increment,</span><br><span class="line">    teacher_name <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    primary <span class="keyword">key</span>(teacher_id)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> student_table2 (</span><br><span class="line">    <span class="comment"># 为本表建立主键约束</span></span><br><span class="line">    student_id <span class="built_in">int</span> auto_increment primary <span class="keyword">key</span>,</span><br><span class="line">    student_name <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    <span class="comment"># 使用表级约束语法建立外键约束，指定约束名为student_teacher_fk</span></span><br><span class="line">    <span class="keyword">constraint</span> student_teacher_fk <span class="keyword">foreign</span> <span class="keyword">key</span>(java_teacher) <span class="keyword">references</span> teacher_table2(teacher_id)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<p>如果需要建立多列组合的外键约束，则必须使用表级约束语法，如下：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 为了保证从表参照的主表存在，通常应该先建主表</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> teacher_table3 (</span><br><span class="line">    teacher_name <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    teacher_pass <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    <span class="comment"># 以两列建立组合主键</span></span><br><span class="line">    primary <span class="keyword">key</span>(teacher_name , teacher_pass)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> student_table3 (</span><br><span class="line">    <span class="comment"># 为主表建立主键约束</span></span><br><span class="line">    student_id <span class="built_in">int</span> auto_increment primary <span class="keyword">key</span>,</span><br><span class="line">    student_name <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    java_teacher_name <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    java_teacher_pass <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    <span class="comment"># 使用表级约束语法建立外键约束，指定联合外键</span></span><br><span class="line">    <span class="keyword">foreign</span> <span class="keyword">key</span> (java_teacher_name , java_teacher_pass) <span class="keyword">references</span> teacher_table3(teacher_name , teacher_pass)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<p>删除外键约束，在<code>alter table</code>后增加<code>drop foreign key 约束名</code></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> student_table3 <span class="keyword">drop</span> <span class="keyword">foreign</span> <span class="keyword">key</span> student_table3_ibfk_1;</span><br></pre></td></tr></table></figure>

<p>增加外键约束如下：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> student_table3 <span class="keyword">add</span> <span class="keyword">foreign</span> <span class="keyword">key</span> (java_teacher_name , java_teacher_pass) <span class="keyword">references</span> teacher_table3(teacher_name , teacher_pass);</span><br></pre></td></tr></table></figure>

<p>外键约束也可以参照自身，称为自关联。例如员工表，员工分为部门经理和普通员工，部门经理和普通员工之间有一对多的关联关系，但都保存在同一个数据表里</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 使用表级约束语法建立外约束键，参照自身</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> foreign_test(</span><br><span class="line">    foreign_id <span class="built_in">int</span> auto_increment primary <span class="keyword">key</span>,</span><br><span class="line">    foreign_name <span class="built_in">varchar</span>(<span class="number">255</span>),</span><br><span class="line">    <span class="comment"># 使用该表的refer_id参照本表的foreign_id列</span></span><br><span class="line">    refer_id <span class="built_in">int</span>,</span><br><span class="line">    <span class="keyword">foreign</span> <span class="keyword">key</span>(refer_id) <span class="keyword">references</span> foreign_test(foreign_id)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/04/29/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day12/" rel="prev" title="Java日拱一卒-day12">
      <i class="fa fa-chevron-left"></i> Java日拱一卒-day12
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/05/05/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day14/" rel="next" title="Java日拱一卒-day14">
      Java日拱一卒-day14 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#NOT-NULL约束"><span class="nav-number">1.</span> <span class="nav-text">NOT NULL约束</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#UNIQUE约束"><span class="nav-number">2.</span> <span class="nav-text">UNIQUE约束</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#PRIMARY-KEY约束"><span class="nav-number">3.</span> <span class="nav-text">PRIMARY KEY约束</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#FOREIGN-KEY约束"><span class="nav-number">4.</span> <span class="nav-text">FOREIGN KEY约束</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="文予"
      src="/uploads/wenyu.png">
  <p class="site-author-name" itemprop="name">文予</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">29</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文予</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>


        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

</body>
</html>
